#include "widget.h"
#include "ui_widget.h"

#include <QProgressBar>
#include <QPropertyAnimation>
#include <QFileDialog>
Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    progressBar = new QProgressBar(this);
    progressBar->setOrientation(Qt::Horizontal);
    progressBar->setFixedSize(734,21);

    // 创建一个QNetworkAccessManager对象，用于处理网络请求
    manager = new QNetworkAccessManager(this);
    // 连接manager的finished信号到保存函数，处理下载完成的操作
    connect(manager, &QNetworkAccessManager::finished, this, &Widget::downloadFinished);
    //连接按钮信号和保存文件的槽函数
    connect(ui->pushButton, &QPushButton::clicked, [ = ]() {
        QString url = ui->lineEdit->text();

        QNetworkRequest request(url);
        QNetworkReply *reply = manager->get(request);
        progressBar->setMaximum(0);
        progressBar->setValue(0);
        connect(reply, &QNetworkReply::downloadProgress, this, &Widget::updateProgress);
    });
}

void Widget::downloadFinished(QNetworkReply *reply)
{
    if (reply->error() != QNetworkReply::NoError) {
        qDebug() << "Download failed: " << reply->errorString();
        return;
    }
    qDebug() << "Download success...";

    //http://n.sinaimg.cn/news/transform/700/w1000h500/20190702/8dba-hzfekep1071042.jpg
    // 获取文件名
    QString filename = reply->url().path().split('/').last();

    // 获取文件后缀名
    QString fileExtension = filename.right(filename.lastIndexOf('.') + 1);

    QFile file("D:\\QT\\QtTen\\Qt8_FileDownload\\saveFile"+filename+fileExtension);

    if (file.open(QIODevice::WriteOnly)) {
        QByteArray data = reply->readAll();
        file.write(data);
        file.close();
        qDebug() << "File saved";
    }
    else
    {
        qDebug() << "Open file err";
    }
    //在主事件循环存在的情况下，可以使用这个函数清理堆空间
    reply->deleteLater();
    //progressBar->hide();隐藏进度条
    QMessageBox::information(this, "提示框", "File saved success...");
}
void Widget::updateProgress(qint64 bytesReceived, qint64 bytesTotal)
{
    progressBar->setMaximum(bytesTotal);
    progressBar->setValue(bytesReceived);
}

Widget::~Widget()
{
    delete ui;
}
